package com.budwk.app.ocr_general;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.aspose.words.*;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.dto.*;
import com.budwk.app.sqfw.models.Sqfw_ImgCallback;
import com.budwk.app.sqfw.models.Sqfw_reportFile;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.util.WordTest;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.google.common.collect.Maps;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.ocr.v1.model.*;
import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import jodd.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import nl.basjes.shaded.org.springframework.core.io.ClassPathResource;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.json.JSONObject;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.OS;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @title: OCRUtil
 * @Author Tan
 * @Date: 2023/6/15 11:38
 * @Version 1.0
 */


@IocBean
@At("/platform/sqfw/tesseract")
@ApiDefinition(tag = "tesseract图片识别")
@Slf4j
public class OCRUtil {

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    SqfwTextReplaceService sqfwTextReplaceService;

    @Inject
    SqfwImgcallbackService sqfwImgcallbackService;

    @Inject
    private HuaweiOssService huaweiOssService;

    @Inject
    private SqfwReportFileService sqfwReportFileService;

    @Inject
    private SysUnitService sysUnitService;

    @Inject
    private PropertiesProxy propertiesProxy;

    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private SysOssService sysOssService;

    //private static final String LibreOfficeDirPath =getConfig("report.LibreOfficeDirPath");;
    private static Map<String, String> map = new HashMap<>();

    private static final String LANG_OPTION = "-l"; //英文字母小写l，并非数字1
    private static final String EOL = System.getProperty("line.separator");
    //private static String tessPath = "C://Program Files//Tesseract-OCR";//ocr默认安装路径
    private static String tessPath = "/data/data/tesseractOcr";//ocr默认安装路径

    private static String transname = "chi_sim";//默认中文语言包，识别中文

    private static final Logger LOGGER = LoggerFactory.getLogger(OCRUtil.class.getName());

    /**
     * recognize text in image
     *
     * @param imageFile   文件路径名
     * @param imageFormat 文件后缀
     * @return text recognized in image
     * @throws Exception
     */

    @At("/tesseractOcr")
    @Ok("json")
    @POST
    @ApiOperation(name = "tesseract图片识别")
    @SLog(tag = "图片识别", value = "${args[0]},${args[1]},${args[2]}")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "imageFile", example = "D:\\CESHI\\IMG\\testImage.jpg"),
                    @ApiFormParam(name = "imageFormat", example = "jpg"),
                    @ApiFormParam(name = "sqfwId", example = "a9ee8e817af04b89938e7f528ca927ca")


            }
    )
    @ApiResponses
    @SaCheckLogin
    public String recognizeText(@Param("imageFile") String imageFile, @Param("imageFormat") String imageFormat, @Param("sqfwId") String sqfwId) throws Exception {

        imageFile = "/data/data/files" + imageFile;

        System.out.println("imageFile===========" + imageFile);

        File image = new File(imageFile);
        File tempImage = new ImageIOHelper().createImage(image, imageFormat);
        Map<String, String> map2 = new HashMap<>();


        String text = ocrImages(tempImage, image);
        if (text != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(text);
            text = m.replaceAll("");
        }

        System.out.println("text==========" + text);

        return text;
    }


    /**
     * recognize text in image
     *
     * @param imageFile   文件路径名
     * @param imageFormat 文件后缀
     * @return text recognized in image
     * @throws Exception
     */

    @At("/showData")
    @Ok("json")
    @POST
    @ApiOperation(name = "tesseract图片识别")
    @SLog(tag = "图片识别", value = "${args[0]},${args[1]},${args[2]}")
    @ApiResponses
    @SaCheckLogin
    public String showData(@Param("imageFile") String imageFile, @Param("imageFormat") String imageFormat, @Param("sqfwId") String sqfwId) throws Exception {
        Map<String, String> map = new HashMap<>();


        File image = new File(imageFile);
        File tempImage = new ImageIOHelper().createImage(image, imageFormat);

        String text = ocrImages(tempImage, image);
        if (text != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(text);
            text = m.replaceAll("");
        }

        System.out.println("text==========" + text);


        //"受理号:2306039577070姓名:女士人BF女业务类别。训务--虎联系方式:86600110[可|热线电活受理方式:地址:观山湖区，金阳北路,爹源国际新城事件类型。民政社区-社区管理-婚恋家庭纪纷间醋措述:观山湖区，爹阳北路,会源国奈新城,110转办案件称沪处发生家许纪纷，民营已到现场处理,要求检关部门做好矛盾纠纷化解工作,请职能部门及时处理。(13837520546)"


        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(text);
        String shoulihao = m.replaceAll("").trim();


        //String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath")+"/file/ocrFile/案件情况说明模板.docx";
        String templateFilePath = "C:\\Users\\CXB-WGW\\Desktop\\案件情况说明模板.docx";


        //String outPath = propertiesProxy.get("cusconfig.report.reportPath")+"/file/ocrFile/outWord/" + shoulihao.substring(0, 13) + "案件情况说明.docx";
        String outPath = "C:\\Users\\CXB-WGW\\Desktop\\file\\ocrWord\\" + "案件情况说明.docx";

        InputStream is1 = new FileInputStream(templateFilePath);
        InputStream is2 = new FileInputStream(templateFilePath);

        // 用来替换变量
        XWPFDocument hdt = new XWPFDocument(is1);
        // 用来输出原格式
        XWPFDocument hdt1 = new XWPFDocument(is2);


        // 替换变量
        replaceText(hdt, map);
        // 替换成原格式
        setStyle(hdt1, hdt);

        // 输出文件
        OutputStream os = new FileOutputStream(outPath);
        hdt.write(os);
        hdt.close();
        hdt1.close();


        return "";
    }


    /**
     * recognize text in image
     *
     * @param imageFile
     * @param imageFormat
     * @param locale
     * @return text recognized in image
     * @throws Exception
     */
    public String recognizeText(File imageFile, String imageFormat, Locale locale) throws Exception {
        File tempImage = new ImageIOHelper(locale).createImage(imageFile, imageFormat);
        return ocrImages(tempImage, imageFile);

    }

    /**
     * @param tempImage
     * @param imageFile
     * @return
     * @throws IOException
     * @throws InterruptedException
     */


    private static String ocrImages(File tempImage, File imageFile) throws IOException, InterruptedException {
        File outputFile = new File(imageFile.getParentFile(), "output");
        //Runtime.getRuntime().exec("attrib "+"\""+outputFile.getAbsolutePath()+"\""+" +H"); //windows设置文件隐藏
        Runtime.getRuntime().exec("chattr " + " +a" + "/" + outputFile.getAbsolutePath() + "/"); //linux设置文件隐藏
        StringBuffer strB = new StringBuffer();
        List<String> cmd = new ArrayList<String>();
        if (OS.isWindows()) {
            cmd.add(tessPath + "//tesseract");
        } else if (OS.isLinux()) {
            cmd.add("tesseract");
        } else {
            cmd.add(tessPath + "//tesseract");
        }
        cmd.add("");
        cmd.add(outputFile.getName());
        cmd.add(LANG_OPTION);
        cmd.add(transname);
        ProcessBuilder pb = new ProcessBuilder();
        pb.directory(imageFile.getParentFile());
        cmd.set(1, tempImage.getName());
        pb.command(cmd);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        int w = process.waitFor();
        tempImage.delete();//删除临时正在工作文件
        if (w == 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath() + ".txt"), "UTF-8"));
            String str;
            while ((str = in.readLine()) != null) {
                strB.append(str).append(
                        EOL);
            }
            in.close();
        } else {
            String msg;
            switch (w) {
                case 1:
                    msg = "Errors accessing files.There may be spaces in your image's filename.";
                    break;
                case 29:
                    msg = "Cannot recongnize the image or its selected region.";
                    break;
                case 31:
                    msg = "Unsupported image format.";
                    break;
                default:
                    msg = "Errors occurred.";
            }
            tempImage.delete();
            throw new RuntimeException(msg);
        }
        new File(outputFile.getAbsolutePath() + ".txt").delete();
        return strB.toString();
    }


    @At("/hwyrecognizeText")
    @Ok("json")
    @POST
    @ApiOperation(name = "华为云通用文字识别")
    @SLog(tag = "华为云通用文字识别", value = "${args[0]},${args[1]},${args[2]}")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "imageFile", example = "D:\\CESHI\\IMG\\testImage.jpg"),
                    @ApiFormParam(name = "imageFormat", example = "jpg")
            }
    )
    @ApiResponses
    @SaCheckLogin
    public Result hwyrecognizeText(@Param("image") String image, @Param("busType") String busType, @Param("busId") String busId) throws Exception {
        //公司
        String ak = "X0LVKFPTLK34BYLR1SDY";
        String sk = "1jOAgxZjfKORNg66PJIs1lgLDspoRnYIcPxolwIN";

        //自己
        /*String ak = "TCIXB25O7ZGGHC1YVOID";
        String sk = "SGTwDJh0JWbqdoP3qMWJ4exZrNVRWw82ceaEorJ5";*/

        image = huaweiOssService.getPwdPath(image);

        String basepic = getImgStrToBase64(image);

        // Init Auth Info
        ICredential credential = getCredential(ak, sk);

        // create ocrClient
        OcrClient ocrClient = getClient(OcrRegion.CN_NORTH_4, credential);


        //private static void generalText(OcrClient ocrClient, String image) {
        RecognizeGeneralTextRequest recognizeGeneralTextRequest = new RecognizeGeneralTextRequest();
        GeneralTextRequestBody requestBody = new GeneralTextRequestBody();
        // requestBody.withUrl(image);
        // recognizeGeneralTextRequest.withBody(requestBody);
        requestBody.setImage(basepic);
        recognizeGeneralTextRequest.setBody(requestBody);
        RecognizeGeneralTextResponse textResponse = null;
        String replaceStr = "";
        Result result = Result.NEW();
        try {
            textResponse = ocrClient.recognizeGeneralText(recognizeGeneralTextRequest);
            System.out.println("text=============" + textResponse.getResult());

            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            StringBuilder wordBuilder = new StringBuilder();
            List<GeneralTextWordsBlockList> textWordBlockList = textResponse.getResult().getWordsBlockList();
            for (GeneralTextWordsBlockList wordBlockList : textWordBlockList) {
                String words = wordBlockList.getWords().replace("：", ":");
                wordBuilder.append(words).append("\n");
            }
            String newStr = "";
            if (wordBuilder.toString().contains("问题描述:")) {
                int lastfuhao = wordBuilder.toString().lastIndexOf("问题描述:");
                int afterfuhao = wordBuilder.toString().lastIndexOf("问题描述:");

                String resultData = wordBuilder.substring(lastfuhao).replaceAll("\n", "");
                String afterData = wordBuilder.substring(0, afterfuhao);
                newStr = afterData + resultData;
            } else {
                newStr = wordBuilder.toString();
            }

            replaceStr = sqfwTextReplaceService.replaceText(newStr, "12345");
            replaceStr = strHandler(replaceStr);
            String imgId = sqfwImgcallbackService.insertByWork(image, replaceStr, SecurityUtil.getUserId(), busType, busId, textResponse.getResult().toString());
            Map map1 = new HashMap();
            map1.put("replaceStr", replaceStr);
            map1.put("imgId", imgId);
            result.addData(map1);

            return result;

            //return  textResponse.getResult();
        } catch (RequestTimeoutException e) {
            LOGGER.error(e.toString());
        } catch (ServiceResponseException e) {
            LOGGER.error(String.valueOf(e.getHttpStatusCode()));
            LOGGER.error(e.getErrorCode());
            LOGGER.error(e.getErrorMsg());
        }
        //}


        return Result.data(0, replaceStr, "识别成功");
    }


    @At("/hwyTableRecognizeText")
    @Ok("json")
    @POST
    @ApiOperation(name = "华为云通用表格识别")
    @SLog(tag = "华为云通用表格识别", value = "${args[0]},${args[1]},${args[2]}")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "image", example = "https://dfsj-standard.obs.cn-south-1.myhuaweicloud.com/test/1.jpg"),
            }
    )
    @ApiResponses
    @SaCheckLogin
    public Result hwyTableRecognizeText(@Param("image") String image, @Param("busType") String busType, @Param("busId") String busId) throws Exception {
        //公司
        String ak = "X0LVKFPTLK34BYLR1SDY";
        String sk = "1jOAgxZjfKORNg66PJIs1lgLDspoRnYIcPxolwIN";

        //自己
        /*String ak = "TCIXB25O7ZGGHC1YVOID";
        String sk = "SGTwDJh0JWbqdoP3qMWJ4exZrNVRWw82ceaEorJ5";*/

        image = huaweiOssService.getPwdPath(image);

        String basepic = getImgStrToBase64(image);

        // Init Auth Info
        ICredential credential = getCredential(ak, sk);

        // create ocrClient
        OcrClient ocrClient = getClient(OcrRegion.CN_NORTH_4, credential);


        //private static void generalText(OcrClient ocrClient, String image) {
        RecognizeGeneralTableRequest recognizeGeneralTableRequest = new RecognizeGeneralTableRequest();
        GeneralTableRequestBody requestBody = new GeneralTableRequestBody();
        // requestBody.withUrl(image);
        // recognizeGeneralTextRequest.withBody(requestBody);
        requestBody.setImage(basepic);
        recognizeGeneralTableRequest.setBody(requestBody);
        RecognizeGeneralTableResponse textResponse = null;
        String replaceStr = "";
        Result result = Result.NEW();
        String newStr = "";
        try {
            textResponse = ocrClient.recognizeGeneralTable(recognizeGeneralTableRequest);
            System.out.println("text=============" + textResponse.getResult());
            replaceStr = textResponse.toString();
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            StringBuilder wordBuilder = new StringBuilder();
            List<WordsRegionList> wordsRegionList = textResponse.getResult().getWordsRegionList();
            //System.out.println("text1111111111============="+ wordsRegionList.get(1).getWordsBlockList().get(5).getWords().replace("\n",""));

            //String newStr = wordsRegionList.get(1).getWordsBlockList().get(5).getWords().replace("\n","");
            for (WordsRegionList wordRegionList : wordsRegionList) {
                List<GeneralTableWordsBlockList> generalTableWordsBlockLists = wordRegionList.getWordsBlockList();
                for (GeneralTableWordsBlockList wordsBlockList : generalTableWordsBlockLists) {
                    String words = wordsBlockList.getWords().toString();
                    wordBuilder.append(words);
                }

            }


            if (wordBuilder.toString().contains("线索基本")) {
                int lastfuhao = wordBuilder.toString().lastIndexOf("线索基本");
                int afterfuhao = wordBuilder.toString().lastIndexOf("当前处理");

                String resultData = wordBuilder.substring(lastfuhao + 7, afterfuhao).replaceAll("\n", "");
                newStr = resultData;
            } else {
                newStr = wordBuilder.toString();
            }

            replaceStr = sqfwTextReplaceService.replaceText(newStr, "12345");
            replaceStr = strHandler(replaceStr);
            String imgId = sqfwImgcallbackService.insertByWork(image, replaceStr, SecurityUtil.getUserId(), busType, busId, textResponse.getResult().toString());
            Map map1 = new HashMap();
            map1.put("replaceStr", replaceStr);
            map1.put("imgId", imgId);
            map1.put("allStr", wordBuilder.toString());
            result.addData(map1);

            return result;

            //return  textResponse.getResult();
        } catch (RequestTimeoutException e) {
            LOGGER.error(e.toString());
        } catch (ServiceResponseException e) {
            LOGGER.error(String.valueOf(e.getHttpStatusCode()));
            LOGGER.error(e.getErrorCode());
            LOGGER.error(e.getErrorMsg());
        }
        //}


        return Result.data(0, replaceStr, "识别成功");
    }


    @At("/hwyLicenseText")
    @Ok("json")
    @POST
    @ApiOperation(name = "华为云通用表格识别")
    @SLog(tag = "华为云通用表格识别", value = "${args[0]},${args[1]},${args[2]}")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "image", example = "https://dfsj-standard.obs.cn-south-1.myhuaweicloud.com/test/1.jpg"),
            }
    )
    @ApiResponses
    @SaCheckLogin
    public Result hwyLicenseText(@Param("image") String image, @Param("busType") String busType, @Param("busId") String busId) throws Exception {
        //公司
        String ak = "X0LVKFPTLK34BYLR1SDY";
        String sk = "1jOAgxZjfKORNg66PJIs1lgLDspoRnYIcPxolwIN";

        //自己
        /*String ak = "TCIXB25O7ZGGHC1YVOID";
        String sk = "SGTwDJh0JWbqdoP3qMWJ4exZrNVRWw82ceaEorJ5";*/

        image = huaweiOssService.getPwdPath(image);

        String basepic = getImgStrToBase64(image);

        // Init Auth Info
        ICredential credential = getCredential(ak, sk);

        // create ocrClient
        OcrClient ocrClient = getClient(OcrRegion.CN_NORTH_4, credential);


        //private static void generalText(OcrClient ocrClient, String image) {
        RecognizeGeneralTableRequest recognizeGeneralTableRequest = new RecognizeGeneralTableRequest();
        GeneralTableRequestBody requestBody = new GeneralTableRequestBody();
        // requestBody.withUrl(image);
        // recognizeGeneralTextRequest.withBody(requestBody);
        requestBody.setImage(basepic);
        recognizeGeneralTableRequest.setBody(requestBody);
        RecognizeGeneralTableResponse textResponse = null;
        String replaceStr = "";
        Result result = Result.NEW();
        String newStr = "";
        try {
            textResponse = ocrClient.recognizeGeneralTable(recognizeGeneralTableRequest);
            System.out.println("text=============" + textResponse.getResult());
            replaceStr = textResponse.toString();
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            StringBuilder wordBuilder = new StringBuilder();
            List<WordsRegionList> wordsRegionList = textResponse.getResult().getWordsRegionList();
            //System.out.println("text1111111111============="+ wordsRegionList.get(1).getWordsBlockList().get(5).getWords().replace("\n",""));

            //String newStr = wordsRegionList.get(1).getWordsBlockList().get(5).getWords().replace("\n","");
            for (WordsRegionList wordRegionList : wordsRegionList) {
                List<GeneralTableWordsBlockList> generalTableWordsBlockLists = wordRegionList.getWordsBlockList();
                for (GeneralTableWordsBlockList wordsBlockList : generalTableWordsBlockLists) {
                    String words = wordsBlockList.getWords().toString();
                    wordBuilder.append(words);
                }

            }


            if (wordBuilder.toString().contains("线索基本")) {
                int lastfuhao = wordBuilder.toString().lastIndexOf("线索基本");
                int afterfuhao = wordBuilder.toString().lastIndexOf("当前处理");

                String resultData = wordBuilder.substring(lastfuhao + 7, afterfuhao).replaceAll("\n", "");
                newStr = resultData;
            } else {
                newStr = wordBuilder.toString();
            }

            replaceStr = sqfwTextReplaceService.replaceText(newStr, "12345");
            replaceStr = strHandler(replaceStr);
            String imgId = sqfwImgcallbackService.insertByWork(image, replaceStr, SecurityUtil.getUserId(), busType, busId, textResponse.getResult().toString());

            replaceStr = replaceStr.replace("\n", "").replace(" ", "").replace("：", ":");
            String csmc = replaceStr.substring(replaceStr.lastIndexOf("经营者名称") + 5, replaceStr.lastIndexOf("许可证编号")).replace(":", "");
            String address = replaceStr.substring(replaceStr.lastIndexOf("住所") + 2, replaceStr.lastIndexOf("投诉举报电话")).replace(":", "");
            String fr = replaceStr.substring(replaceStr.lastIndexOf("法定代表人") + 10, replaceStr.lastIndexOf("日常监督管理")).replace(":", "");

            Map map1 = new HashMap();
            map1.put("replaceStr", replaceStr);
            map1.put("imgId", imgId);
            map1.put("csmc", csmc);// 场所名称
            map1.put("address", address);// 地址
            map1.put("fr", fr);// 法人/负责人
            result.addData(map1);

            return result;

            //return  textResponse.getResult();
        } catch (RequestTimeoutException e) {
            LOGGER.error(e.toString());
        } catch (ServiceResponseException e) {
            LOGGER.error(String.valueOf(e.getHttpStatusCode()));
            LOGGER.error(e.getErrorCode());
            LOGGER.error(e.getErrorMsg());
        }
        //}


        return Result.data(0, replaceStr, "识别成功");
    }


    @At("/getRecResult")
    @Ok("json")
    @POST
    @ApiOperation(name = "华为云图片识别")
    @SLog(tag = "华为云图片识别", value = "${args[0]}")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "imageFile", example = "D:\\CESHI\\IMG\\testImage.jpg"),
                    @ApiFormParam(name = "imageFormat", example = "jpg")
            }
    )
    @ApiResponses
    @SaCheckLogin
    public Result getRecResult(@Param("sqfwId") String sqfwId) throws Exception {

        Cnd cnd = Cnd.NEW();
        cnd.and("business_id", "=", sqfwId);
        Sqfw_ImgCallback sqfw_imgCallback = sqfwImgcallbackService.fetch(cnd);

        Map<String, String> resultMap = Maps.newHashMap();
        if (sqfw_imgCallback != null) {
            String text = sqfw_imgCallback.getText();
            text = text.replace("：", ":");
            String shoulihao = "";
            if (StringUtils.isNotBlank(text)) {
                int last = text.lastIndexOf("问题描述:");
                text = text.substring(last).replace("问题描述:", "");
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(text);
                text = m.replaceAll("");


                String regEx = "[^0-9]";
                Pattern p1 = Pattern.compile(regEx);
                Matcher m1 = p1.matcher(sqfw_imgCallback.getText());
                shoulihao = m1.replaceAll("").trim();

            }
            shoulihao = shoulihao.substring(0, 13);

            resultMap.put("text", text);
            resultMap.put("shoulihao", shoulihao);
        } else {
            // wzy 2023-10-12 如果该任务没有照片的话就直接取任务中的 record_text的值
            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);
            if (serviceRecord != null) resultMap.put("text", serviceRecord.getRecording_text());
            else resultMap.put("text", "");
            resultMap.put("shoulihao", "");
        }

        return Result.data(resultMap);
    }


    @At("/toWordPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "12345生成文档")
    @SLog(tag = "12345生成文档", value = "${args[0]}")
    @ApiResponses
    @SaCheckLogin
    public Result<?> toWordPdf(@Param("..") SqfwWordContentDTO sqfwWordContentDTO) throws Exception {
        Map<String, String> map = new HashMap<>();

        String picStr = "";
        String newpicStr = sqfwWordContentDTO.getPic();
        System.out.println("picStr==============" + picStr);

        String[] picss = newpicStr.split(",");
        int a = 0;
        int b = 0;
        int j = picss.length;
        for (String pic : picss) {
            //判断图片类型并做路径拼接
            if (pic.endsWith("png")) {
                Date date = new Date();
                String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".png";
                downloadPictureToServer(pic, img);
                if (a != 0) {
                    picStr = picStr + "," + img;
                } else {
                    picStr = img;
                }
                a++;
            }
            if (pic.endsWith("jpg") || pic.endsWith("jpeg")) {
                Date date = new Date();
                // downloadPictureToServer(pic,propertiesProxy.get("cusconfig.report.reportPath")+"/file/ocrFile/image/"+date+".jpg");
                String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".jpg";
                downloadPictureToServer(pic, img);
                if (b != 0) {
                    picStr = picStr + "," + img;
                } else {
                    picStr = img;
                }
                b++;
            }
        }

        String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/ocrFile/案件情况说明模板.docx";
        //String templateFilePath = "C:\\Users\\XYPC-WZY\\Desktop\\案件情况说明模板.docx";

        String fileNameOf12345 = sqfwWordContentDTO.getAcceptedNum() + "案件情况说明.docx";
        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/ocrFile/outWord/" + fileNameOf12345;
        //String outPath = "C:\\Users\\XYPC-WZY\\Desktop\\"+"案件情况说明.docx";

        InputStream is1 = new FileInputStream(templateFilePath);
        InputStream is2 = new FileInputStream(templateFilePath);

        // 用来替换变量
        XWPFDocument hdt = new XWPFDocument(is1);
        // 用来输出原格式
        XWPFDocument hdt1 = new XWPFDocument(is2);


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String czsj = simpleDateFormat.format(sqfwWordContentDTO.getDisposalTime());
        String flowStartTime = czsj.substring(0, 4) + "年" + czsj.substring(5, 7) + "月" + czsj.substring(8, 10) + "日" + czsj.substring(11, 16) + "分";

        String lksj = simpleDateFormat.format(sqfwWordContentDTO.getInscribeTime());
        String timestr = lksj.substring(0, 4) + "年" + lksj.substring(5, 7) + "月" + lksj.substring(8, 10) + "日";


        //设置word更新变量
        map.put("reference", sqfwWordContentDTO.getAcceptedNum());
        map.put("czbm", sqfwWordContentDTO.getDisposalDepartment());
        map.put("flowStartTime", flowStartTime);
        map.put("czfs", sqfwWordContentDTO.getDisposalWay());
        map.put("taskde", sqfwWordContentDTO.getReflectedContent().replace(" ", ""));
        map.put("text", sqfwWordContentDTO.getResult());
        map.put("last", sqfwWordContentDTO.getDisposalCondition().replace(" ", ""));
        map.put("create", timestr);
        if (StringUtils.isNotBlank(picStr)) {
            map.put("annex", "附件：");
        } else {
            map.put("annex", null);
        }

        System.out.println("result============" + sqfwWordContentDTO.getResult());

        File outFilePath = new File(outPath);
        try {
            // 生成新的文件并写到硬盘
            XWPFTemplate.compile(templateFilePath).render(map, new FileOutputStream(outFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 替换成原格式
        //setStyle(hdt1, hdt);

        // 输出文件
        //OutputStream os = new FileOutputStream(outPath);
        //hdt.write(os);
        hdt.close();
        hdt1.close();


        //插入图片
        if (StringUtils.isNotBlank(sqfwWordContentDTO.getPic())) {
            insertImageWorld(outPath, picStr);
        } else {
            try {
                // 加载Word文档
                InputStream fis = new FileInputStream(outPath);
                //FileInputStream fis = new FileInputStream(outPath);
                XWPFDocument document = new XWPFDocument(fis);


                int summary = document.getBodyElements().size();
                document.removeBodyElement(summary - 1);

                // 保存文档
                OutputStream fos = new FileOutputStream(outPath);
                document.write(fos);
                fis.close();
                fos.close();

                System.out.println("最后一页删除成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/ocrFile/outPdf/" + fileNameOf12345.replace("docx", "pdf");

        //将word转成pdf
        WordTest.wordToPdf(outPath, pdf);

        //上传到对象存储上
        SysOss wordSysOss = sysOssService.upload(FileUtil.file(outPath), fileNameOf12345);

        SysOss pdfSysOss = sysOssService.upload(FileUtil.file(pdf), fileNameOf12345.replace("docx", "pdf"));

        Map<String, Object> mapPath = new HashMap<>();
        mapPath.put("uploadresultWord", sysOssToString(wordSysOss));
        mapPath.put("uploadresultPdf", sysOssToString(pdfSysOss));

        return Result.data(mapPath);
    }


    @At("/toEightWordPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成八单一表文档")
    @SLog(tag = "生成八单一表文档", value = "${args[0]}")
    @ApiFormParams()
    @ApiResponses
    @SaCheckLogin
    public Result toEightWordPdf(@Param("..") SqfwEightWordContentDTO sqfwEightWordContentDTO) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();

        //String picStr = "D:\\CESHI\\IMG\\c869-a80eae75a6860207eea18519c98b8ac6.jpg,D:\\CESHI\\IMG\\test.jpg,D:\\CESHI\\IMG\\heguang1.png,D:\\CESHI\\IMG\\heguang2.png";
        //String picStr = "G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg,G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg";

        //String templateFilePath = "/data/shequ/file/file/ocrFile/案件情况说明模板.docx";
        /*String templateFilePath = "C:\\Users\\CXB-WGW\\Desktop\\入户调查单.docx";
        String outPath = "C:\\Users\\CXB-WGW\\Desktop\\file\\ocrWord\\入户调查单.docx";

        String templateFilePath1 = "C:\\Users\\CXB-WGW\\Desktop\\入户家访单.docx";
        String outPath1 = "C:\\Users\\CXB-WGW\\Desktop\\file\\ocrWord\\入户家访单.docx";*/

        String RHDCBFileName = "婚恋家庭纠纷入户调查表-" + sqfwEightWordContentDTO.getDcPerson() + ".docx";
        String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/入户调查单.docx";
        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/outWord/" + RHDCBFileName;

        String RHJFDFileName = "婚恋家庭纠纷入户家访单-" + sqfwEightWordContentDTO.getDcPerson() + ".docx";
        String templateFilePath1 = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/入户家访单.docx";
        String outPath1 = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/outWord/" + RHJFDFileName;

        //String outPath = "/data/shequ/file/file/ocrFile/outWord/" + SecurityUtil.getUserUsername() + sqfwWordContentDTO.getAcceptedNum() + "案件情况说明.docx";


        //入户调查
        InputStream is1 = new FileInputStream(templateFilePath);
        InputStream is2 = new FileInputStream(templateFilePath);

        // 用来替换变量
        XWPFDocument hdt = new XWPFDocument(is1);
        // 用来输出原格式
        XWPFDocument hdt1 = new XWPFDocument(is2);

        //入户家访
        InputStream isjf = new FileInputStream(templateFilePath1);
        InputStream isjf2 = new FileInputStream(templateFilePath1);

        // 用来替换变量
        XWPFDocument hdtjf = new XWPFDocument(isjf);
        // 用来输出原格式
        XWPFDocument hdtjf1 = new XWPFDocument(isjf2);


        Sys_unit sys_unit = sysUnitService.fetch(SecurityUtil.getUnitId());

        Cnd cnd = Cnd.NEW();
        if (!Strings.isNotBlank(sys_unit.getParentId())) {
            cnd.and("unitid", "=", SecurityUtil.getUnitId());
        } else {

            cnd.and("unitid", "=", sys_unit.getParentId());
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //入户时间
        String rhsj = simpleDateFormat.format(sqfwEightWordContentDTO.getRhTime());
        String ruhuTime = rhsj.substring(0, 4) + "年" + rhsj.substring(5, 7) + "月" + rhsj.substring(8, 10) + "日";

        //签收时间
        String qssj = simpleDateFormat.format(sqfwEightWordContentDTO.getQsTime());
        String qianshouTime = qssj.substring(0, 4) + "年" + qssj.substring(5, 7) + "月" + qssj.substring(8, 10) + "日";

        //入户调查
        map.put("time", ruhuTime);
        map.put("dcunit", sqfwEightWordContentDTO.getDcUnit());
        map.put("dcperson", sqfwEightWordContentDTO.getDcPerson());
        map.put("sfzname", sqfwEightWordContentDTO.getSfzname());
        map.put("sex", sqfwEightWordContentDTO.getSex());
        map.put("age", sqfwEightWordContentDTO.getAge());
        map.put("hyzk", sqfwEightWordContentDTO.getHyzk());
        map.put("landphone", sqfwEightWordContentDTO.getLandphone());
        map.put("address", sqfwEightWordContentDTO.getAddress());
        map.put("jftype", sqfwEightWordContentDTO.getJftype());
        map.put("jbqk", sqfwEightWordContentDTO.getJbqk());
        map.put("jfqk", sqfwEightWordContentDTO.getJfqk());
        map.put("clqk", sqfwEightWordContentDTO.getClqk());


        //入户家访
        map1.put("jsunit", sqfwEightWordContentDTO.getJsunit());
        map1.put("qsr", sqfwEightWordContentDTO.getQsr());
        map1.put("qstime", qianshouTime);
        map1.put("jfdx", sqfwEightWordContentDTO.getJfdx());
        map1.put("jfyq", sqfwEightWordContentDTO.getJfyq());
        map1.put("gzqkjxg", sqfwEightWordContentDTO.getGzqkjxg());
        map1.put("jfdw", sqfwEightWordContentDTO.getJfdw());
        map1.put("jfry", sqfwEightWordContentDTO.getJfry());


        File outFilePath = new File(outPath);
        File outFilePath1 = new File(outPath1);
        try {
            // 生成新的文件并写到硬盘
            XWPFTemplate.compile(templateFilePath).render(map, new FileOutputStream(outFilePath));
            XWPFTemplate.compile(templateFilePath1).render(map1, new FileOutputStream(outFilePath1));

        } catch (IOException e) {
            e.printStackTrace();
        }

        hdt.close();
        hdt1.close();

        hdtjf.close();
        hdtjf1.close();

        //insertImageWorld(outPath,picStr);

        String pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/outPdf/" + RHDCBFileName.replace("docx", "pdf");
        String pdf1 = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/outPdf/" + RHJFDFileName.replace("docx", "pdf");

        WordTest.wordToPdf(outPath, pdf);
        WordTest.wordToPdf(outPath1, pdf1);

        //上传到对象存储上
        SysOss uploadresultWord = sysOssService.upload(FileUtil.file(outPath), RHDCBFileName);
        SysOss uploadresultPdf = sysOssService.upload(FileUtil.file(pdf), RHDCBFileName.replace("docx", "pdf"));
        SysOss uploadresultWord1 = sysOssService.upload(FileUtil.file(outPath1), RHJFDFileName);
        SysOss uploadresultPdf1 = sysOssService.upload(FileUtil.file(pdf1), RHJFDFileName.replace("docx", "pdf"));


        Map<String, Object> mapPath = new HashMap<>();
        mapPath.put("uploadresultdiaochaWord", sysOssToString(uploadresultWord));
        mapPath.put("uploadresultdiaochaPdf", sysOssToString(uploadresultPdf));
        mapPath.put("uploadresultjiafangWord", sysOssToString(uploadresultWord1));
        mapPath.put("uploadresultjiafangPdf", sysOssToString(uploadresultPdf1));

        if (!sqfwEightWordContentDTO.isContain()) {
            Map<String, Object> map2 = toClueWordPdf(sqfwEightWordContentDTO);
            mapPath.put("uploadresultxiansuoWord", map2.get("uploadresultxiansuoWord"));
            mapPath.put("uploadresultxiansuoPdf", map2.get("uploadresultxiansuoPdf"));
        }
        return Result.data(mapPath);
    }

    @At("/toCustomReportWordPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成自定义简报文档")
    @SLog(tag = "生成自定义简报文档", value = "${args[0]}")
    @ApiFormParams()
    @ApiResponses
    @SaCheckLogin
    public Result toCustomReportWordPdf(@Param("..") SqfwCustomReportDTO sqfwCustomReportDTO) throws Exception {
        Map<String, Object> map = new HashMap<>();


        String templateFilePath = "";
        if (sqfwCustomReportDTO.getStartLine() && sqfwCustomReportDTO.getEndLine()) {
            templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/CustomReportFile/自定义简报-页眉页脚.docx";

        }
        if (!sqfwCustomReportDTO.getStartLine() && sqfwCustomReportDTO.getEndLine()) {
            templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/CustomReportFile/自定义简报-页脚.docx";

        }
        if (sqfwCustomReportDTO.getStartLine() && !sqfwCustomReportDTO.getEndLine()) {
            templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/CustomReportFile/自定义简报-页眉.docx";

        }
        if (!sqfwCustomReportDTO.getStartLine() && !sqfwCustomReportDTO.getEndLine()) {
            templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/CustomReportFile/自定义简报.docx";
        }
        //String templateFilePath = "C:\\Users\\CXB-WGW\\Desktop\\自定义简报.docx";


        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/CustomReportFile/outWord/" + sqfwCustomReportDTO.getHeaderTitle() + "-" + SecurityUtil.getUserUsername() + ".docx";
        //String outPath = "C:\\Users\\CXB-WGW\\Desktop\\file\\ocrWord\\自定义简报.docx";

        InputStream is1 = new FileInputStream(templateFilePath);

        // 用来替换变量
        XWPFDocument hdt = new XWPFDocument(is1);
        /*HWPFDocument hdt2=new HWPFDocument(is1);
        Range hdt =hdt2.getRange();
        hdt.get*/
        // 用来输出原格式


        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getHeaderTitle())) {
            map.put("headerTitle", sqfwCustomReportDTO.getHeaderTitle());
        } else {
            map.put("headerTitle", null);
        }
        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getHeaderLeft())) {
            map.put("headerLeft", sqfwCustomReportDTO.getHeaderLeft());
        } else {
            map.put("headerLeft", null);
        }
        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getHeaderRight())) {
            map.put("headerRight", sqfwCustomReportDTO.getHeaderRight());
        } else {
            map.put("headerRight", null);
        }
        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getContentTitle())) {
            map.put("contentTitle", sqfwCustomReportDTO.getContentTitle());
        } else {
            map.put("contentTitle", null);
        }
        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getInformationContent())) {
            map.put("informationContent", sqfwCustomReportDTO.getInformationContent());
        } else {
            map.put("informationContent", null);
        }
        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getFooterLeft())) {
            map.put("footerLeft", sqfwCustomReportDTO.getFooterLeft());
        } else {
            map.put("footerLeft", null);
        }
        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getFooterRight())) {
            map.put("footerRight", sqfwCustomReportDTO.getFooterRight());
        } else {
            map.put("footerRight", null);
        }
        if (sqfwCustomReportDTO.getStartLine()) {

            try {
                // 加载Word文档
               /* FileInputStream fis = new FileInputStream(templateFilePath);
                XWPFDocument document = new XWPFDocument(fis);*/

                // 遍历所有段落
                for (XWPFParagraph paragraph : hdt.getParagraphs()) {
                    // 获取段落中的文本
                    String text = paragraph.getText();


                    // 检查是否包含指定内容
                    if (text.contains("{{startLine}}")) {
                        // 移除段落中的所有run
                        while (paragraph.getRuns().size() > 0) {
                            paragraph.removeRun(0);
                        }

                        // 创建一个运行并设置其文本为"___________________"
                        //paragraph.setAlignment(ParagraphAlignment.CENTER);
                        XWPFRun run = paragraph.createRun();

                        run.setText("　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　");


                        // 设置运行的字体颜色为红色
                        //run.setText("——————————————————————————");
                        run.setTextPosition(4);
                        run.setUnderline(UnderlinePatterns.SINGLE);
                        run.setColor("FF0000"); // 红色
                        run.setBold(true);
                        run.setFontSize(70);


                        break;
                    }
                }

                // 保存修改后的Word文档到文件
                FileOutputStream out = new FileOutputStream(new File(outPath));
                hdt.write(out);
                out.close();

                System.out.println("Word文档修改成功！");
            } catch (Exception ex) {
                System.out.println("发生异常: " + ex.getMessage());
                ex.printStackTrace();
            }
            map.put("startLine", null);
        } else {
            map.put("startLine", null);
        }
        if (sqfwCustomReportDTO.getEndLine()) {

            try {
                // 遍历所有段落
                for (XWPFParagraph paragraph : hdt.getParagraphs()) {
                    // 获取段落中的文本
                    String text = paragraph.getText();

                    // 检查是否包含指定内容
                    if (text.contains("{{endLine}}")) {
                        // 移除段落中的所有run
                        while (paragraph.getRuns().size() > 0) {
                            paragraph.removeRun(0);
                        }

                        // 创建一个运行并设置其文本为"___________________"
                        XWPFRun run = paragraph.createRun();

                        run.setText("　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　");
                        //paragraph.setBorderBottom(Borders.THICK);

                        // 设置运行的字体颜色为红色
                        //run.setText("——————————————————————————");
                        run.setTextPosition(4);
                        run.setUnderline(UnderlinePatterns.SINGLE);
                        run.setColor("FF0000"); // 红色
                        run.setBold(true);
                        run.setFontSize(70);
                        break;
                    }
                }

                // 保存修改后的Word文档到文件
                FileOutputStream out = new FileOutputStream(new File(outPath));
                hdt.write(out);
                out.close();

                System.out.println("Word文档修改成功！");
            } catch (Exception ex) {
                System.out.println("发生异常: " + ex.getMessage());
                ex.printStackTrace();
            }

        } else {
            map.put("endLine", null);
        }
        if (StringUtils.isNotBlank(sqfwCustomReportDTO.getPic())) {
            Integer a = 0;
            Integer b = 0;
            String newpicStr = sqfwCustomReportDTO.getPic();
            String picStr = "";
            String[] picss = newpicStr.split(",");
            PictureType pictureType = null;
            for (String pic : picss) {
                //判断图片类型并做路径拼接
                if (pic.endsWith("png")) {
                    pictureType = PictureType.PNG;
                    Date date = new Date();
                    String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".png";
                    downloadPictureToServer(pic, img);
                    if (a != 0) {
                        picStr = picStr + "," + img;
                    } else {
                        picStr = img;
                    }
                    a++;

                }
                if (pic.endsWith("jpg") || pic.endsWith("jpeg")) {
                    pictureType = PictureType.JPEG;
                    Date date = new Date();
                    // downloadPictureToServer(pic,propertiesProxy.get("cusconfig.report.reportPath")+"/file/ocrFile/image/"+date+".jpg");
                    String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".jpg";
                    downloadPictureToServer(pic, img);
                    if (b != 0) {
                        picStr = picStr + "," + img;
                    } else {
                        picStr = img;
                    }
                    b++;

                }
            }


            String[] images = picStr.split(",");
            for (int i = 0; i < images.length; i++) {
                try {
                    // 图片的处理
                    Map mapSize = resizeTable(images[i]);
                    Double.parseDouble(mapSize.get("height").toString());
                    PictureRenderData pictureRenderData = Pictures.ofStream(new FileInputStream(images[i]), pictureType)
                            .size(Integer.parseInt(mapSize.get("width").toString()), Integer.parseInt(mapSize.get("height").toString())).create();
                    map.put("pic" + i, pictureRenderData);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }


            }


        }


        File outFilePath = new File(outPath);
        try {
            String newpicStr = sqfwCustomReportDTO.getPic();
            String picStr = "";
            String[] picss = newpicStr.split(",");
            int forToImage = 0;
            if (picss.length % 2 == 0) {
                forToImage = picss.length / 2;
            } else {
                forToImage = picss.length / 2 + 1;
            }

            List<XWPFTable> tables = hdt.getTables();
            XWPFTable table = tables.get(0);
            for (int i = 7; i > forToImage - 1; i--) {
                table.removeRow(i);
            }

            hdt.write(new FileOutputStream(outFilePath));


            // 生成新的文件并写到硬盘
            XWPFTemplate.compile(outPath).render(map, new FileOutputStream(outFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        hdt.close();


        String wordFileName = SecurityUtil.getUserUsername() + sqfwCustomReportDTO.getHeaderTitle() + "自定义简报.docx";
        String pdfFileName = wordFileName.replace("docx", "pdf");
        String pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/CustomReportFile/outPdf/" + pdfFileName;
        //String pdf="C:\\Users\\CXB-WGW\\Desktop\\file\\ocrWord\\自定义pdf.pdf";

        //将word以流的形式转出pdf
        InputStream asposeLicInputStream = null;
        //去掉水印
        asposeLicInputStream = new ClassPathResource("/license.xml").getInputStream();
        License asposeLic = new License();
        asposeLic.setLicense(asposeLicInputStream);

        com.aspose.words.Document wordDocument = new com.aspose.words.Document(outPath);
        ParagraphFormat pf = wordDocument.getStyles().getDefaultParagraphFormat();
        pf.clearFormatting();
        wordDocument.save(pdf, SaveFormat.PDF);

        asposeLicInputStream.close();


        String outPathDoc = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/CustomReportFile/outWord/" + SecurityUtil.getUserUsername() + sqfwCustomReportDTO.getHeaderTitle() + "自定义简报.doc";


        convertDocxToDoc(outPath, outPathDoc);

        //上传到对象存储上
        String uploadresultWord = sysOssToString(sysOssService.upload(FileUtil.file(outPathDoc), wordFileName));
        String uploadresultPdf = sysOssToString(sysOssService.upload(FileUtil.file(pdf), pdfFileName));

        Map<String, Object> mapPath = new HashMap<>();
        mapPath.put("uploadresultWord", uploadresultWord);
        mapPath.put("uploadresultPdf", uploadresultPdf);

        return Result.data(mapPath);
    }


    /*** 合并单元格** @param table         表格对象* @param beginRowIndex 开始行索引* @param endRowIndex   结束行索引* @param colIndex      合并列索引*/
    public static void mergeCell(XWPFTable table, int beginRowIndex, int endRowIndex, int colIndex) {
        if (beginRowIndex == endRowIndex || beginRowIndex > endRowIndex) {
            return;
        }//合并行单元格的第一个单元格
        CTVMerge startMerge = CTVMerge.Factory.newInstance();
        startMerge.setVal(STMerge.RESTART);//合并行单元格的第一个单元格之后的单元格
        CTVMerge endMerge = CTVMerge.Factory.newInstance();
        endMerge.setVal(STMerge.CONTINUE);
        table.getRow(beginRowIndex).getCell(colIndex).getCTTc().getTcPr().setVMerge(startMerge);
        for (int i = beginRowIndex + 1; i <= endRowIndex; i++) {
            table.getRow(i).getCell(colIndex).getCTTc().getTcPr().setVMerge(endMerge);
        }
    }


    @At("/ocrTestToText")
    @Ok("json")
    @POST
    @ApiOperation(name = "华为云通用文字识别")
    @SLog(tag = "华为云通用文字识别", value = "${args[0]}")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "image", example = "D:\\CESHI\\IMG\\testImage.jpg"),
            }
    )
    @ApiResponses
    @SaCheckLogin
    public Result ocrTestToText(@Param("image") String image) throws Exception {
        //公司
        String ak = "X0LVKFPTLK34BYLR1SDY";
        String sk = "1jOAgxZjfKORNg66PJIs1lgLDspoRnYIcPxolwIN";

        //自己
        /*String ak = "TCIXB25O7ZGGHC1YVOID";
        String sk = "SGTwDJh0JWbqdoP3qMWJ4exZrNVRWw82ceaEorJ5";*/
        String basepic = getImgStrToBase64Test(image);

        // Init Auth Info
        ICredential credential = getCredential(ak, sk);

        // create ocrClient
        OcrClient ocrClient = getClient(OcrRegion.CN_NORTH_4, credential);


        RecognizeGeneralTextRequest recognizeGeneralTextRequest = new RecognizeGeneralTextRequest();
        GeneralTextRequestBody requestBody = new GeneralTextRequestBody();
        requestBody.setImage(basepic);
        recognizeGeneralTextRequest.setBody(requestBody);
        RecognizeGeneralTextResponse textResponse = null;
        String replaceStr = "";
        Result result = Result.NEW();
        try {
            textResponse = ocrClient.recognizeGeneralText(recognizeGeneralTextRequest);
            System.out.println("text=============" + textResponse.getResult());

            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            StringBuilder wordBuilder = new StringBuilder();
            List<GeneralTextWordsBlockList> textWordBlockList = textResponse.getResult().getWordsBlockList();
            for (GeneralTextWordsBlockList wordBlockList : textWordBlockList) {
                String words = wordBlockList.getWords();
                wordBuilder.append(words).append("\n");
            }
            String newStr = "";
            newStr = wordBuilder.toString();
            Map map1 = new HashMap();
            map1.put("ocrResult", newStr);
            result.addData(map1);

            return result;

        } catch (RequestTimeoutException e) {
            LOGGER.error(e.toString());
        } catch (ServiceResponseException e) {
            LOGGER.error(String.valueOf(e.getHttpStatusCode()));
            LOGGER.error(e.getErrorCode());
            LOGGER.error(e.getErrorMsg());
        }
        //}


        return Result.data(0, replaceStr, "识别成功");
    }


    public Map<String, Object> toClueWordPdf(@Param("..") SqfwEightWordContentDTO sqfwEightWordContentDTO) throws Exception {
        Map<String, Object> map2 = new HashMap<>();

        String XSBGDFileName = "婚恋家庭纠纷线索报告单-" + sqfwEightWordContentDTO.getDcPerson() + ".docx";
        String templateFilePath2 = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/线索报告单.docx";
        String outPath2 = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/outWord/" + XSBGDFileName;


        //线索报告
        InputStream isxs = new FileInputStream(templateFilePath2);
        InputStream isxs2 = new FileInputStream(templateFilePath2);

        // 用来替换变量
        XWPFDocument hdtxs = new XWPFDocument(isxs);
        // 用来输出原格式
        XWPFDocument hdtxs1 = new XWPFDocument(isxs2);


        Sys_unit sys_unit = sysUnitService.fetch(SecurityUtil.getUnitId());

        Cnd cnd = Cnd.NEW();
        if (!Strings.isNotBlank(sys_unit.getParentId())) {
            cnd.and("unitid", "=", SecurityUtil.getUnitId());
        } else {

            cnd.and("unitid", "=", sys_unit.getParentId());
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //入户时间
        String rhsj = simpleDateFormat.format(sqfwEightWordContentDTO.getRhTime());
        String ruhuTime = rhsj.substring(0, 4) + "年" + rhsj.substring(5, 7) + "月" + rhsj.substring(8, 10) + "日";
        String hzsj = rhsj.substring(0, 4) + "/" + rhsj.substring(5, 7) + "/" + rhsj.substring(8, 10) + " " + rhsj.substring(11, 13) + ":" + rhsj.substring(14, 16);

        //签收时间
        String qssj = simpleDateFormat.format(sqfwEightWordContentDTO.getQsTime());
        String qianshouTime = qssj.substring(0, 4) + "年" + qssj.substring(5, 7) + "月" + qssj.substring(8, 10) + "日";

        //线索报告
        map2.put("unit", sqfwEightWordContentDTO.getDcUnit());
        map2.put("time", hzsj);
        map2.put("getchannel", sqfwEightWordContentDTO.getHzqd());
        map2.put("xsjbqk", sqfwEightWordContentDTO.getJfyq());
        map2.put("dqclqk", sqfwEightWordContentDTO.getClqk());
        map2.put("bgdwjbr", sqfwEightWordContentDTO.getBgdwjbr());

        File outFilePath2 = new File(outPath2);
        try {
            XWPFTemplate.compile(templateFilePath2).render(map2, new FileOutputStream(outFilePath2));
        } catch (IOException e) {
            e.printStackTrace();
        }

        hdtxs.close();
        hdtxs1.close();

        String pdf2 = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/eightFile/outPdf/" + XSBGDFileName.replace("docx", "pdf");

        WordTest.wordToPdf(outPath2, pdf2);

        //上传到对象存储上
        SysOss uploadresultWord2 = sysOssService.upload(FileUtil.file(outPath2), XSBGDFileName);
        SysOss uploadresultPdf2 = sysOssService.upload(FileUtil.file(pdf2), XSBGDFileName.replace("docx", "pdf"));

        Map<String, Object> mapPath = new HashMap<>();
        mapPath.put("uploadresultxiansuoWord", sysOssToString(uploadresultWord2));
        mapPath.put("uploadresultxiansuoPdf", sysOssToString(uploadresultPdf2));

        return mapPath;
    }


    @At("/toGeneralWordPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成通用模板")
    @SLog(tag = "生成通用模板", value = "${args[0]}")
    @ApiFormParams()
    @ApiResponses
    @SaCheckLogin
    public Result toGeneralWordPdf(@Param("..") SqfwGeneralWordPdfDto sqfwGeneralWordPdfDto) throws Exception {
        Map<String, String> map = new HashMap<>();
        String picStr = "";
        String newpicStr = sqfwGeneralWordPdfDto.getPics();
        System.out.println("picStr==============" + picStr);

        String[] picss = newpicStr.split(",");

        Integer a = 0;
        Integer b = 0;
        Integer j = picss.length;
        for (String pic : picss) {
            //判断图片类型并做路径拼接

            if (pic.endsWith("png")) {
                Date date = new Date();
                String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".png";
                downloadPictureToServer(pic, img);
                if (a != 0) {
                    picStr = picStr + "," + img;
                } else {
                    picStr = img;
                }
                a++;

            }
            if (pic.endsWith("jpg") || pic.endsWith("jpeg")) {
                Date date = new Date();
                // downloadPictureToServer(pic,propertiesProxy.get("cusconfig.report.reportPath")+"/file/ocrFile/image/"+date+".jpg");
                String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".jpg";
                downloadPictureToServer(pic, img);
                if (b != 0) {
                    picStr = picStr + "," + img;
                } else {
                    picStr = img;
                }
                b++;

            }
        }

        String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/generalFile/通用模板.docx";
        //String templateFilePath = "C:\\Users\\CXB-WGW\\Desktop\\案件情况说明模板.docx";

        String ZDYFileName = sqfwGeneralWordPdfDto.getType() + "完成情况-" + SecurityUtil.getUserUsername() + ".docx";    // 自定义文件名称
        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/generalFile/outWord/" + ZDYFileName;
        //String outPath = "C:\\Users\\CXB-WGW\\Desktop\\file\\ocrWord\\"+"案件情况说明.docx";

        InputStream is1 = new FileInputStream(templateFilePath);
        InputStream is2 = new FileInputStream(templateFilePath);

        // 用来替换变量
        XWPFDocument hdt = new XWPFDocument(is1);
        // 用来输出原格式
        XWPFDocument hdt1 = new XWPFDocument(is2);


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cjsj = simpleDateFormat.format(new Date());
        String flowStartTime = cjsj.substring(0, 4) + "年" + cjsj.substring(5, 7) + "月" + cjsj.substring(8, 10) + "日";


        //设置word更新变量
        map.put("type", sqfwGeneralWordPdfDto.getType());
        map.put("rwnr", sqfwGeneralWordPdfDto.getRwnr());
        map.put("wcqk", sqfwGeneralWordPdfDto.getWcqk());
        map.put("wcjg", sqfwGeneralWordPdfDto.getWcjg());
        map.put("name", sqfwGeneralWordPdfDto.getName());
        map.put("create", flowStartTime);

        if (StringUtils.isNotBlank(picStr)) {
            map.put("annex", "附件：");
        } else {
            map.put("annex", null);
        }

        File outFilePath = new File(outPath);
        try {
            // 生成新的文件并写到硬盘
            XWPFTemplate.compile(templateFilePath).render(map, new FileOutputStream(outFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }


        // 替换成原格式
        //setStyle(hdt1, hdt);

        // 输出文件
        //OutputStream os = new FileOutputStream(outPath);
        //hdt.write(os);
        hdt.close();
        hdt1.close();


        //插入图片
        insertImageWorld(outPath, picStr);


        if (!StringUtils.isNotBlank(picStr)) {
            InputStream isStream = new FileInputStream(outPath);

            // 用来替换变量
            XWPFDocument hdtDoc = new XWPFDocument(isStream);
            try {
                int summary = hdtDoc.getBodyElements().size();
                hdtDoc.removeBodyElement(summary - 1);
            } catch (Exception e) {
                e.printStackTrace();
            }

            hdtDoc.close();
        }


        String pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/generalFile/outPdf/" + ZDYFileName.replace("docx", "pdf");

        //Word2PdfJacobUtil2(outPath, pdf);
        //String pdfPath="C:\\Users\\CXB-WGW\\Desktop\\file\\pdf\\案件情况说明.pdf";


        //wordToPdf(outPath,pdf);
        //word2pdf(outPath,pdf);

        //将word转成pdf
        WordTest.wordToPdf(outPath, pdf);


        //上传到对象存储上
        SysOss uploadresultWord = sysOssService.upload(FileUtil.file(outPath), ZDYFileName);
        SysOss uploadresultPdf = sysOssService.upload(FileUtil.file(pdf), ZDYFileName.replace("docx", "pdf"));

        Map<String, Object> mapPath = new HashMap<>();
        mapPath.put("uploadresultWord", sysOssToString(uploadresultWord));
        mapPath.put("uploadresultPdf", sysOssToString(uploadresultPdf));

        return Result.data(mapPath);
    }


    @At("/toReportWordPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成日报")
    @SLog(tag = "生成日报", value = "${args[0]}")
    @ApiFormParams()
    @ApiResponses
    @SaCheckLogin
    public Result toReportWordPdf(@Param("..") SqfwDailyDTO sqfwDailyDTO) throws Exception {
        Map<String, String> map = new HashMap<>();

        //"受理号:2306039577070姓名:女士人BF女业务类别。训务--虎联系方式:86600110[可|热线电活受理方式:地址:观山湖区，金阳北路,爹源国际新城事件类型。民政社区-社区管理-婚恋家庭纪纷间醋措述:观山湖区，爹阳北路,会源国奈新城,110转办案件称沪处发生家许纪纷，民营已到现场处理,要求检关部门做好矛盾纠纷化解工作,请职能部门及时处理。(13837520546)"

        String picStr = "";
        String newpicStr = sqfwDailyDTO.getPics();
        System.out.println("picStr==============" + picStr);


        // String a="https://dfsj-standard.obs.cn-south-1.myhuaweicloud.com:443/2023/06/26/21dd19db400647aa803d648e7d767602.png,https://dfsj-standard.obs.cn-south-1.myhuaweicloud.com:443/2023/06/26/54afaf6507934d769b1b6f074a3f4924.png";
        String[] picss = newpicStr.split(",");


        Integer a = 0;
        Integer b = 0;
        Integer j = picss.length;
        for (String pic : picss) {
            //判断图片类型并做路径拼接

            if (pic.endsWith("png")) {
                Date date = new Date();
                String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".png";
                downloadPictureToServer(pic, img);
                if (a != 0) {
                    picStr = picStr + "," + img;
                } else {
                    picStr = img;
                }
                a++;

            }
            if (pic.endsWith("jpg") || pic.endsWith("jpeg")) {
                Date date = new Date();
                // downloadPictureToServer(pic,propertiesProxy.get("cusconfig.report.reportPath")+"/file/ocrFile/image/"+date+".jpg");
                String img = propertiesProxy.get("cusconfig.report.reportPath") + "/file/ocrFile/image/" + date.getTime() + ".jpg";
                downloadPictureToServer(pic, img);
                if (b != 0) {
                    picStr = picStr + "," + img;
                } else {
                    picStr = img;
                }
                b++;

            }
        }

        String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/dailyFile/日报模板.docx";
        //String templateFilePath = "C:\\Users\\CXB-WGW\\Desktop\\案件情况说明模板.docx";


        String RBFileName = SecurityUtil.getUserUsername() + "日报" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".docx";
        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/dailyFile/outWord/" + RBFileName;
        //String outPath = "C:\\Users\\CXB-WGW\\Desktop\\file\\ocrWord\\"+"案件情况说明.docx";

        InputStream is1 = new FileInputStream(templateFilePath);
        InputStream is2 = new FileInputStream(templateFilePath);

        // 用来替换变量
        XWPFDocument hdt = new XWPFDocument(is1);
        // 用来输出原格式
        XWPFDocument hdt1 = new XWPFDocument(is2);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cjsj = simpleDateFormat.format(new Date());
        String flowStartTime = cjsj.substring(0, 4) + "年" + cjsj.substring(5, 7) + "月" + cjsj.substring(8, 10) + "日";


        //设置word更新变量
        map.put("gznr", sqfwDailyDTO.getTaskContent());
        map.put("wcqk", sqfwDailyDTO.getWcqk());
        map.put("name", sqfwDailyDTO.getReportName());
        map.put("create", sqfwDailyDTO.getReportTime());


        if (StringUtils.isNotBlank(picStr)) {
            map.put("annex", "附件：");
        } else {
            map.put("annex", null);
        }

        File outFilePath = new File(outPath);
        try {
            // 生成新的文件并写到硬盘
            XWPFTemplate.compile(templateFilePath).render(map, new FileOutputStream(outFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        hdt.close();
        hdt1.close();

        if (StringUtils.isNotBlank(sqfwDailyDTO.getPics())) {
            //插入图片
            insertImageWorld(outPath, picStr);
            //删除特殊字符段落
            //replaceSpecialChar(outPath,"\u000B");
        } else {

            try {
                // 加载Word文档

                InputStream fis = new FileInputStream(outPath);
                //FileInputStream fis = new FileInputStream(outPath);
                XWPFDocument document = new XWPFDocument(fis);


                int summary = document.getBodyElements().size();
                document.removeBodyElement(summary - 1);

                // 保存文档
                OutputStream fos = new FileOutputStream(outPath);
                document.write(fos);
                fis.close();
                fos.close();

                System.out.println("最后一页删除成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        String pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/file/dailyFile/outPdf/" + RBFileName.replace("docx", "pdf");

        //将word转成pdf
        WordTest.wordToPdf(outPath, pdf);

        //上传到对象存储上
        SysOss uploadresultWord = sysOssService.upload(FileUtil.file(outPath), RBFileName);
        SysOss uploadresultPdf = sysOssService.upload(FileUtil.file(pdf), RBFileName.replace("docx", "pdf"));

        Map<String, Object> mapPath = new HashMap<>();
        mapPath.put("uploadresultWord", sysOssToString(uploadresultWord));
        mapPath.put("uploadresultPdf", sysOssToString(uploadresultPdf));

        return Result.data(mapPath);
    }


    @At("/insertEightData")
    @Ok("json")
    @POST
    @ApiOperation(name = "插入文档数据")
    @SLog(tag = "八单一表分享记录", value = "${args[0]}")
    @ApiFormParams()
    @ApiResponses
    @SaCheckLogin
    public Result insertEightData(@Param("..") SqfwEightWordContentDTO sqfwEightWordContentDTO) {
        JSONObject jsonObject = new JSONObject(sqfwEightWordContentDTO);

        Sqfw_reportFile sqfw_reportFile = new Sqfw_reportFile();
        sqfw_reportFile.setSqfwId(sqfwEightWordContentDTO.getSqfwId());
        sqfw_reportFile.setWorkOrderId(sqfwEightWordContentDTO.getWorkId());
        sqfw_reportFile.setCreateDate(new Date());
        sqfw_reportFile.setCreateBy(SecurityUtil.getUserId());
        sqfw_reportFile.setServiceRecordType(sqfwEightWordContentDTO.getServiceRecordType());
        sqfw_reportFile.setDocDetail(jsonObject.toString());
        sqfw_reportFile.setPdfFileUrl(sqfwEightWordContentDTO.getPdfUrl());
        sqfw_reportFile.setWordFileUrl(sqfwEightWordContentDTO.getWorkUrl());
        sqfw_reportFile.setReportName(sqfwEightWordContentDTO.getReportName());
        sqfwReportFileService.insert(sqfw_reportFile);

        return Result.success();
    }


    @At("/insertOneTwoData")
    @Ok("json")
    @POST
    @ApiOperation(name = "插入文档数据")
    @SLog(tag = "12345和其他分享记录", value = "${args[0]}")
    @ApiFormParams()
    @ApiResponses
    @SaCheckLogin
    public Result insertOneTwoData(@Param("..") SqfwWordContentDTO sqfwWordContentDTO) {
        JSONObject jsonObject = new JSONObject(sqfwWordContentDTO);
        Sqfw_reportFile sqfw_reportFile = new Sqfw_reportFile();
        sqfw_reportFile.setSqfwId(sqfwWordContentDTO.getSqfwId());
        sqfw_reportFile.setWorkOrderId(sqfwWordContentDTO.getWorkId());
        sqfw_reportFile.setCreateDate(new Date());
        sqfw_reportFile.setCreateBy(SecurityUtil.getUserId());
        sqfw_reportFile.setServiceRecordType(sqfwWordContentDTO.getServiceRecordType());
        sqfw_reportFile.setDocDetail(jsonObject.toString());
        sqfw_reportFile.setPdfFileUrl(sqfwWordContentDTO.getPdfUrl());
        sqfw_reportFile.setWordFileUrl(sqfwWordContentDTO.getWorkUrl());
        sqfw_reportFile.setReportName(sqfwWordContentDTO.getReportName());
        sqfwReportFileService.insert(sqfw_reportFile);

        return Result.success();
    }


    @At("/uploadpath")
    @Ok("json")
    @POST
    @ApiOperation(name = "tesseract图片识别")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "image", example = "D:\\CESHI\\IMG\\guybkjhink.jpg"),
                    @ApiFormParam(name = "imageFormat", example = "jpg"),
                    @ApiFormParam(name = "sqfwId", example = "a9ee8e817af04b89938e7f528ca927ca")
            }
    )
    @ApiResponses
    @SaCheckLogin
    public Result<?> uploadpath(@Param("image") String image) {
        //上传到对象存储上
        SysOss uploadresultWord = sysOssService.upload(FileUtil.file(image));
        Map<String, Object> mapPath = new HashMap<>();
        mapPath.put("uploadresultWord", sysOssToString(uploadresultWord));
        return Result.data(mapPath);
    }

    public static void insertImageWorld(String templateFilePath, String picStr) {
        try {
            Map<String, Object> map = new HashMap<>();

            //String picStr="G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg,G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg";
            String outPath = templateFilePath;

            String[] images = picStr.split(",");

            InputStream is1 = new FileInputStream(templateFilePath);
            // 用来替换变量
            XWPFDocument hdt = new XWPFDocument(is1);

            // 创建一个段落
            XWPFParagraph p = hdt.createParagraph();

            p.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun r = p.createRun();

            for (int i = 0; i < images.length; i++) {
                int format;

                if (images[i].endsWith(".emf")) {
                    format = Document.PICTURE_TYPE_EMF;
                } else if (images[i].endsWith(".wmf")) {
                    format = Document.PICTURE_TYPE_WMF;
                } else if (images[i].endsWith(".pict")) {
                    format = Document.PICTURE_TYPE_PICT;
                } else if (images[i].endsWith(".jpeg") || images[i].endsWith(".jpg")) {
                    format = Document.PICTURE_TYPE_JPEG;
                } else if (images[i].endsWith(".png")) {
                    format = Document.PICTURE_TYPE_PNG;
                } else if (images[i].endsWith(".dib")) {
                    format = Document.PICTURE_TYPE_DIB;
                } else if (images[i].endsWith(".gif")) {
                    format = Document.PICTURE_TYPE_GIF;
                } else if (images[i].endsWith(".tiff")) {
                    format = Document.PICTURE_TYPE_TIFF;
                } else if (images[i].endsWith(".eps")) {
                    format = Document.PICTURE_TYPE_EPS;
                } else if (images[i].endsWith(".bmp")) {
                    format = Document.PICTURE_TYPE_BMP;
                } else if (images[i].endsWith(".wpg")) {
                    format = Document.PICTURE_TYPE_WPG;
                } else {
                    System.err.println("Unsupported picture: " + images[i] +
                            ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
                    continue;
                }
                // 设置标题
                //  r.setText(imgFile);
                // 换行
                //r.addBreak();


                Map map1 = resize(images[i]);
                double width = Double.parseDouble(map1.get("width").toString());
                double height = Double.parseDouble(map1.get("height").toString());

                try (FileInputStream is = new FileInputStream(images[i])) {
                    // 320x200 pixels
                    r.addPicture(is, format, images[i], Units.toEMU(width), Units.toEMU(height));
                } catch (InvalidFormatException e) {
                    throw new RuntimeException(e);
                }
                // 换页 一张图片一页
                if (i != images.length - 1) {
                    r.addBreak(BreakType.PAGE);
                }
            }

            try (FileOutputStream out = new FileOutputStream(templateFilePath)) {
                hdt.write(out);
            }


           /* String pdf = "G:\\test\\" + "案件情况说明.docx".replace("docx", "pdf");

            WordTest.wordToPdf(outPath, pdf);*/

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


    }


    public static void replaceSpecialChar(String templateFilePath, String specialChar) {

        try {
            // 读取 Word 文档
            FileInputStream fis = new FileInputStream(templateFilePath);
            XWPFDocument document = new XWPFDocument(fis);

            // 遍历文档中的段落
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            Iterator<XWPFParagraph> iter = paragraphs.iterator();

            while (iter.hasNext()) {
                XWPFParagraph paragraph = iter.next();

                // 检查段落文本是否包含软回车符号（换行符）
                if (paragraph.getText().contains(specialChar)) {
                    iter.remove(); // 删除包含软回车的段落
                }
            }

            // 保存修改后的文档
            FileOutputStream fos = new FileOutputStream(templateFilePath);
            document.write(fos);
            fos.close();

            fis.close();
            System.out.println("包含软回车的行已删除，并保存为 output.docx");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static void insertImageTableWorld(String templateFilePath, String picStr, XWPFDocument hdt) {
        try {


            Map<String, Object> map = new HashMap<>();

            //String picStr="G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg,G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg";

            String[] images = picStr.split(",");

            for (int i = 0; i < images.length; i++) {

            }

            int imageInt = 0;
            int forToImage = 0;
            if (images.length % 2 == 0) {
                forToImage = images.length / 2;
            } else {
                forToImage = images.length / 2 + 1;
            }

            for (XWPFParagraph paragraph : hdt.getParagraphs()) {
                String text = paragraph.getText();
                if (text.contains("{{annex}}")) {
                    while (paragraph.getRuns().size() > 0) {
                        paragraph.removeRun(0);
                    }


                    XWPFRun r1 = paragraph.createRun();


                    int pos = hdt.getPosOfParagraph(paragraph);

                    //根据图片数量生成n行2列的表格
                    XWPFTable table = hdt.createTable(forToImage, 2);
                    hdt.insertTable(pos, table);

                    table.setTableAlignment(TableRowAlign.CENTER);

                    // 双实线边框
                    String bolderType = "double";
                    CTTblBorders borders = table.getCTTbl().getTblPr().addNewTblBorders();
                    // 设置上下左右外边框
                    CTBorder lBorder = borders.addNewLeft();
                    lBorder.setVal(STBorder.Enum.forString(bolderType));
                    lBorder.setSz(new BigInteger("1"));
                    lBorder.setColor("FFFFFF");

                    CTBorder rBorder = borders.addNewRight();
                    rBorder.setVal(STBorder.Enum.forString(bolderType));
                    rBorder.setSz(new BigInteger("1"));
                    rBorder.setColor("FFFFFF");

                    CTBorder tBorder = borders.addNewTop();
                    tBorder.setVal(STBorder.Enum.forString(bolderType));
                    tBorder.setSz(new BigInteger("1"));
                    tBorder.setColor("FFFFFF");

                    CTBorder bBorder = borders.addNewBottom();
                    bBorder.setVal(STBorder.Enum.forString(bolderType));
                    bBorder.setSz(new BigInteger("1"));
                    bBorder.setColor("FFFFFF");


                    int a = 0;
                    for (int i = 0; i < forToImage; i++) {
                        for (int j = 0; j < 2; j++) {
                            if (i % 2 == 0) {
                                a = 0;
                            } else {
                                a = 1;
                            }
                            //表示获取第几行第几列
                            XWPFTableRow tableRow = table.getRow(i);
                            XWPFTableCell tableCell = tableRow.getCell(j);
                            XWPFParagraph paragraph11 = tableCell.addParagraph();

                            // 创建一个段落
                            //XWPFParagraph p = hdt.createParagraph();

                            paragraph11.setAlignment(ParagraphAlignment.CENTER);
                            XWPFRun r = paragraph11.createRun();


                            //for (int i=0;i<images.length;i++) {
                            int format;

                            if (images[i].endsWith(".emf")) {
                                format = Document.PICTURE_TYPE_EMF;
                            } else if (images[i].endsWith(".wmf")) {
                                format = Document.PICTURE_TYPE_WMF;
                            } else if (images[i].endsWith(".pict")) {
                                format = Document.PICTURE_TYPE_PICT;
                            } else if (images[i].endsWith(".jpeg") || images[i].endsWith(".jpg")) {
                                format = Document.PICTURE_TYPE_JPEG;
                            } else if (images[i].endsWith(".png")) {
                                format = Document.PICTURE_TYPE_PNG;
                            } else if (images[i].endsWith(".dib")) {
                                format = Document.PICTURE_TYPE_DIB;
                            } else if (images[i].endsWith(".gif")) {
                                format = Document.PICTURE_TYPE_GIF;
                            } else if (images[i].endsWith(".tiff")) {
                                format = Document.PICTURE_TYPE_TIFF;
                            } else if (images[i].endsWith(".eps")) {
                                format = Document.PICTURE_TYPE_EPS;
                            } else if (images[i].endsWith(".bmp")) {
                                format = Document.PICTURE_TYPE_BMP;
                            } else if (images[i].endsWith(".wpg")) {
                                format = Document.PICTURE_TYPE_WPG;
                            } else {
                                System.err.println("Unsupported picture: " + images[i] +
                                        ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
                                continue;
                            }

                            try (FileInputStream is = new FileInputStream(images[i])) {
                                // 320x200 pixels
                                //if (images.length%2!=0){
                                r.addPicture(is, format, images[imageInt], Units.toEMU(200), Units.toEMU(150));
                                imageInt++;
                                //}
                            } catch (InvalidFormatException e) {
                                throw new RuntimeException(e);
                            }
                            // 换页 一张图片一页
                           /* if (i != images.length - 1) {
                                r.addBreak(BreakType.PAGE);
                            }*/
                            //}

                            try (FileOutputStream out = new FileOutputStream(templateFilePath)) {
                                hdt.write(out);
                            }


           /* String pdf = "G:\\test\\" + "案件情况说明.docx".replace("docx", "pdf");

            WordTest.wordToPdf(outPath, pdf);*/
                        }

                    }

                    break;
                }

            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }


    private static Map resize(String urlpath) throws IOException {
        Map<String, Integer> map = new HashMap<>();
        URL url = new URL("file:///" + urlpath);
        byte[] bytes = IOUtils.toByteArray(url.openStream());
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        BufferedImage img = javax.imageio.ImageIO.read(bis);
        int width = img.getWidth();
        int height = img.getHeight();

        int picHeight = 0;
        int picWidth = 0;
        //下面按照图片的实际大小进行同比例缩放
        if (width > height) {
            picWidth = 400;
            picHeight = picWidth * height / width;

        } else if (width < height) {
            picHeight = 500;
            picWidth = picHeight * width / height;
        } else {
            picHeight = 400;
            picWidth = 400;
        }

        //下次读取该ByteArrayInputStream 之前一定要调用reset进行复位，这样才能读到图片所有数据
        bis.reset();

        map.put("width", picWidth);
        map.put("height", picHeight);
        return map;
    }


    private static Map resizeTable(String urlpath) throws IOException {
        Map<String, Integer> map = new HashMap<>();
        URL url = new URL("file:///" + urlpath);
        byte[] bytes = IOUtils.toByteArray(url.openStream());
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        BufferedImage img = javax.imageio.ImageIO.read(bis);
        int width = img.getWidth();
        int height = img.getHeight();

        int picHeight = 0;
        int picWidth = 0;
        //下面按照图片的实际大小进行同比例缩放
        if (width > height) {
            picWidth = 280;
            picHeight = picWidth * height / width;

        } else if (width < height) {
            picHeight = 280;
            picWidth = picHeight * width / height;
        } else {
            picHeight = 280;
            picWidth = 280;
        }

        //下次读取该ByteArrayInputStream 之前一定要调用reset进行复位，这样才能读到图片所有数据
        bis.reset();

        map.put("width", picWidth);
        map.put("height", picHeight);
        return map;
    }


    public static void pdf2png(String pdfPath) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(pdfPath);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            int pdfIndex = pdfPath.lastIndexOf(".");
            String pdfName = pdfPath.substring(0, pdfIndex);

            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图

                ImageIO.write(image, "png", new File(pdfName + "_" + (i + 1) + "." + "png"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void insertImageWorld(String templateFilePath) {
        try {
            Map<String, Object> map = new HashMap<>();

            String picStr = "G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg,G:\\test\\test.png,G:\\test\\MSI.png,G:\\test\\MSI_MAG.png,G:\\test\\MSI_PRO.jpg";
            String outPath = templateFilePath;

            String[] images = picStr.split(",");

            InputStream is1 = new FileInputStream(templateFilePath);
            // 用来替换变量
            XWPFDocument hdt = new XWPFDocument(is1);

            // 创建一个段落
            XWPFParagraph p = hdt.createParagraph();

            XWPFRun r = p.createRun();

            for (String imgFile : images) {
                int format;

                if (imgFile.endsWith(".emf")) {
                    format = Document.PICTURE_TYPE_EMF;
                } else if (imgFile.endsWith(".wmf")) {
                    format = Document.PICTURE_TYPE_WMF;
                } else if (imgFile.endsWith(".pict")) {
                    format = Document.PICTURE_TYPE_PICT;
                } else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) {
                    format = Document.PICTURE_TYPE_JPEG;
                } else if (imgFile.endsWith(".png")) {
                    format = Document.PICTURE_TYPE_PNG;
                } else if (imgFile.endsWith(".dib")) {
                    format = Document.PICTURE_TYPE_DIB;
                } else if (imgFile.endsWith(".gif")) {
                    format = Document.PICTURE_TYPE_GIF;
                } else if (imgFile.endsWith(".tiff")) {
                    format = Document.PICTURE_TYPE_TIFF;
                } else if (imgFile.endsWith(".eps")) {
                    format = Document.PICTURE_TYPE_EPS;
                } else if (imgFile.endsWith(".bmp")) {
                    format = Document.PICTURE_TYPE_BMP;
                } else if (imgFile.endsWith(".wpg")) {
                    format = Document.PICTURE_TYPE_WPG;
                } else {
                    System.err.println("Unsupported picture: " + imgFile +
                            ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
                    continue;
                }
                // 设置标题
                //  r.setText(imgFile);
                // 换行
                r.addBreak();
                try (FileInputStream is = new FileInputStream(imgFile)) {
                    // 320x200 pixels


                    r.addPicture(is, format, imgFile, Units.toEMU(320), Units.toEMU(200));
                } catch (InvalidFormatException e) {
                    throw new RuntimeException(e);
                }
                // 换页 一张图片一页
                r.addBreak(BreakType.PAGE);
            }

            try (FileOutputStream out = new FileOutputStream(templateFilePath)) {
                hdt.write(out);
            }


            String pdf = "G:\\test\\" + "案件情况说明.docx".replace("docx", "pdf");

            WordTest.wordToPdf(outPath, pdf);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }


    public static void word2pdf(String wordPath, String pdfPath) throws IOException {
        // 参考：https:
        //blog.csdn.net/ka3p06/article/details/125476270 通过documents4j实现
        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream(wordPath);
            // 转换后pdf生成地址
            outputStream = new FileOutputStream(pdfPath);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }
    }


    /**
     * @param urlList 图片链接地址，如：https://game.gtimg.cn/images/lol/act/img/rune/Predator.png
     * @param path    文件存放路径及名称，如：/springtest/item/2021-12-24/1640323863344/F00413-6.png
     * @Title: downloadPicture
     * @Description: 链接url下载图片到服务器
     */
    public static void downloadPictureToServer(String urlList, String path) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断文本中是否包含$
     *
     * @param text 文本
     * @return 包含返回true, 不包含返回false
     */
    public static boolean checkText(String text) {
        boolean check = false;
        if (text.indexOf("$") != -1) {
            check = true;
        }
        return check;
    }


    public static Integer sufIndex(String tessPath) {

        int pictureType = 0;
        if (tessPath.endsWith(".emf"))
            pictureType = XWPFDocument.PICTURE_TYPE_EMF;
        else if (tessPath.endsWith(".wmf"))
            pictureType = XWPFDocument.PICTURE_TYPE_WMF;
        else if (tessPath.endsWith(".pict"))
            pictureType = XWPFDocument.PICTURE_TYPE_PICT;
        else if (tessPath.endsWith(".jpeg") || tessPath.endsWith(".jpg"))
            pictureType = XWPFDocument.PICTURE_TYPE_JPEG;
        else if (tessPath.endsWith(".png"))
            pictureType = XWPFDocument.PICTURE_TYPE_PNG;
        else if (tessPath.endsWith(".dib"))
            pictureType = XWPFDocument.PICTURE_TYPE_DIB;
        else if (tessPath.endsWith(".gif"))
            pictureType = XWPFDocument.PICTURE_TYPE_GIF;
        else if (tessPath.endsWith(".tiff"))
            pictureType = XWPFDocument.PICTURE_TYPE_TIFF;
        else if (tessPath.endsWith(".eps"))
            pictureType = XWPFDocument.PICTURE_TYPE_EPS;
        else if (tessPath.endsWith(".bmp"))
            pictureType = XWPFDocument.PICTURE_TYPE_BMP;
        else if (tessPath.endsWith(".wpg"))
            pictureType = XWPFDocument.PICTURE_TYPE_WPG;

        return pictureType;

    }


    /**
     * 本地或网络图片转base64
     */
    public static String getImgStrToBase64(String imgStr) {
        InputStream inputStream = null;
        byte[] buffer = null;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) {
            //判断网络链接图片文件/本地目录图片文件
            if (imgStr.startsWith("http://") || imgStr.startsWith("https://")) {
                // 创建URL
                URL url = new URL(imgStr);
                // 创建链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                inputStream = conn.getInputStream();
                // 将内容读取内存中
                buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                buffer = outputStream.toByteArray();
            } else {
                inputStream = new FileInputStream(imgStr);
                int count = 0;
                while (count == 0) {
                    count = inputStream.available();
                }
                buffer = new byte[count];
                inputStream.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 对字节数组Base64编码
        Base64.Encoder encode = Base64.getEncoder();
        return encode.encodeToString(buffer);
    }


    /**
     * 本地或网络图片转base64
     */
    public static String getImgStrToBase64Test(String imgStr) {
        InputStream inputStream = null;
        byte[] buffer = null;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) {
            //判断网络链接图片文件/本地目录图片文件
            if (imgStr.startsWith("http://") || imgStr.startsWith("https://")) {
                // 创建URL
                URL url = new URL(imgStr);
                // 创建链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                inputStream = conn.getInputStream();
                // 将内容读取内存中
                buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                buffer = outputStream.toByteArray();
            } else {
                SysOssService staticSysOssService = (SysOssService) NutzIocUtils.getBeanByType(SysOssService.class);
                String uploadresultWord = sysOssToString(staticSysOssService.upload(FileUtil.file(imgStr)));
                System.out.println("imgUrl=====" + uploadresultWord);
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(uploadresultWord);
                String dataStr = jsonObject.getString("data");
                com.alibaba.fastjson.JSONObject jsonObjectData = JSON.parseObject(dataStr);

                // 创建URL
                URL url = new URL(jsonObjectData.getString("url"));
                // 创建链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                inputStream = conn.getInputStream();
                // 将内容读取内存中
                buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                buffer = outputStream.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 对字节数组Base64编码
        Base64.Encoder encode = Base64.getEncoder();
        return encode.encodeToString(buffer);
    }


    public static ICredential getCredential(String ak, String sk) {
        return new BasicCredentials().withAk(ak).withSk(sk);
    }

    public static OcrClient getClient(Region region, ICredential auth) {
        return OcrClient.newBuilder().withCredential(auth).withRegion(region).build();
    }

    private static void setStyle(XWPFDocument tempDoc, XWPFDocument doc) {
        Iterator<XWPFParagraph> iterator = tempDoc.getParagraphsIterator();
        Iterator<XWPFParagraph> iterator2 = doc.getParagraphsIterator();
        XWPFParagraph para;
        XWPFParagraph para2;
        while (iterator.hasNext() && iterator2.hasNext()) {
            para = iterator.next();
            para2 = iterator2.next();
            setStyleInPara(para, para2);
        }
    }

    private static void setStyleInPara(XWPFParagraph para, XWPFParagraph para2) {
        List<XWPFRun> runs = para.getRuns();
        List<XWPFRun> runs2 = para2.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            XWPFRun run2 = runs2.get(i);
            run2.getCTR().setRPr(run.getCTR().getRPr());
        }
    }


    private static void replaceText(XWPFDocument doc, Map<String, String> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            replaceInPara(para, params);
        }
    }


    private static void replaceInPara(XWPFParagraph para, Map<String, String> params) {
        List<XWPFRun> runs = para.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.toString();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (runText.contains(entry.getKey())) {
                    try {
                        para.removeRun(i);
                        // 重新插入run里内容格式可能与原来模板的格式不一致
                        para.insertNewRun(i).setText(runText.replace(entry.getKey(), entry.getValue()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    public static String strHandler(String content) {
        String[] split = content.split(":");
        for (int i = 0; i < split.length; i++) {
            String s1 = split[i];
            if (s1.startsWith("\n")) {
                s1 = s1.substring(1);
            }
            if (i < split.length - 1) {
                split[i] = s1 + ":";
            }
        }
        StringBuilder result = new StringBuilder();
        for (String s1 : split) {
            s1 = s1.replaceAll("(\n){2,}", "\n");
            result.append(s1);
        }
        return result.toString();
    }

    public static void convertDocxToDoc(String docxFilePath, String docOutputPath) throws Exception {
        // 加载.docx文件
        com.aspose.words.Document docxDocument = new com.aspose.words.Document(docxFilePath);

        // 保存为.doc文件
        com.aspose.words.Document docDocument = (com.aspose.words.Document) docxDocument.deepClone(true);
        docDocument.save(docOutputPath);
    }

    /**
     * wzy 2023-10-13 这个破方法就是为针对之前写这个类的人上传文件之后不解析，直接把上传返回的
     * 字符串直接传给前端，我简直服了。
     *
     * @param sysOss 上传对象
     * @return 结果
     */
    private static String sysOssToString(SysOss sysOss) {
        Map<String, Object> resultMap = Maps.newHashMap();
        sysOss.setFileName(sysOss.getOriginalName());
        resultMap.put("data", sysOss);
        return com.alibaba.fastjson.JSONObject.toJSONString(resultMap);
    }
}
